//
//  StatusListViewModel.swift
//  SinaWebo
//
//  Created by mis on 16/3/22.
//  Copyright © 2016年 mis. All rights reserved.
//

import UIKit
import AFNetworking
import SVProgressHUD
import SDWebImage

class StatusListViewModel: NSObject {
    class func loadData(since_id: Int, max_id: Int, finished: (array: [Status]?, error: NSError?) -> ()) {
        let urlString = "2/statuses/home_timeline.json";
        guard let token = UserAccountViewModel().access_token else {
            SVProgressHUD.showErrorWithStatus("你还没有登录")
            return
        }
        var parameters = ["access_token": token]
        if since_id > 0 {
            parameters["since_id"] = "\(since_id)"
        }
        if max_id > 0 {
            parameters["max_id"] = "\(max_id - 1)"
        }
        
        NetworkTools.sharedTools.requestJsonDict(HTTPMethod.GET, urlString: urlString, parameters: parameters) { (result, error) -> () in
            if error != nil {
                finished(array: nil, error: error)
                return
            }
            if let array = result!["statuses"] as? [[String: AnyObject]] {
                var list = [Status]()
                for item in array {
                    let s = Status(dict: item)
                    list.append(s)
                }
                StatusListViewModel.loadImage(list, finished: finished)
            }
        }
    }

    class private func loadImage(array: [Status], finished: (array: [Status]?, error: NSError?) -> ()) {
        
        if array.count == 0 {
            finished(array: nil, error: nil)
            return
        }
        
        let group = dispatch_group_create()
        
        for s in array {
            if let imageurls = s.pictureURLs {
                if imageurls.count != 1 {
                    continue
                }
                for url in imageurls {
                    dispatch_group_enter(group)
                    SDWebImageManager.sharedManager().downloadImageWithURL(url, options: [], progress: nil, completed: { (_, _, _, _, _) -> Void in
                        print("单张图片加载成功")
                        dispatch_group_leave(group)
                    })
                }
            }
        }
        dispatch_group_notify(group, dispatch_get_main_queue()) { () -> Void in
            print("所有图片异步加载成功")
            finished(array: array, error: nil)
        }
        
    }
}
